package com.luckyframe.common.netty.jmeter;

import com.luckyframe.common.netty.NettyChannelMap;
import com.luckyframe.project.jmeter.jmeterNode.domain.JmeterNode;
import com.luckyframe.project.jmeter.jmeterNode.enums.JmeterNodeStatus;
import com.luckyframe.project.jmeter.jmeterNode.service.IJmeterNodeService;
import io.netty.channel.Channel;
import io.netty.channel.socket.SocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class JmeterChannelMap {

    //logger
    private static final Logger log = LoggerFactory.getLogger(NettyChannelMap.class);

    //ip===>JmeterNode
    private static Map<String, Channel> map= new ConcurrentHashMap<>();

    @Autowired
    private IJmeterNodeService jmeterNodeService;


    public  void remove(SocketChannel socketChannel){

        for (@SuppressWarnings("rawtypes") Map.Entry entry:map.entrySet()){
            if (entry.getValue()==socketChannel){
                log.info("#############客户端下线##############");
                log.info("下线主机名为："+entry.getKey());

                JmeterNode node=jmeterNodeService.selectJmeterNodeById(Long.valueOf(entry.getKey().toString()));
                if(node!=null)
                {
                    node.setStatus(JmeterNodeStatus.DOWN.getCode());
                    jmeterNodeService.updateJmeterNode(node);
                }
                map.remove(entry.getKey());
                socketChannel.close();
            }
        }
    }


    public void put(String clientId, Channel channel) {
        map.put(clientId,channel);
    }

    public Channel get(String clientId){
        return map.get(clientId);
    }


}
